package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.SysDoctorSchedule;
import com.ruoyi.system.domain.SysDoctorScheduleQuery;
import com.ruoyi.system.domain.DoctorSchedules;
import com.ruoyi.system.mapper.SysDoctorScheduleMapper;
import com.ruoyi.system.service.ISysDoctorScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public  class SysDoctorScheduleServiceImpl implements ISysDoctorScheduleService {
    @Autowired
    private SysDoctorScheduleMapper mapper;

    @Override
    public List<DoctorSchedules> selectScheduleList(SysDoctorScheduleQuery query) {
        List<SysDoctorSchedule> flatList = mapper.selectScheduleList(query);
        Map<Long, DoctorSchedules> doctorMap = new LinkedHashMap<>();
        for (SysDoctorSchedule s : flatList) {
            DoctorSchedules doc = doctorMap.computeIfAbsent(s.getDoctorId(), id -> {
                DoctorSchedules d = new DoctorSchedules();
                d.setDoctorId(s.getDoctorId());
                d.setDoctorName(s.getDoctorName());
                d.setDeptName(s.getDeptName());
                d.setSchedules(new ArrayList<>());
                return d;
            });
            doc.getSchedules().add(s);
        }
        return new ArrayList<>(doctorMap.values());
    }
    @Override
    public SysDoctorSchedule selectScheduleDetail(Long doctorId, Date scheduleDate) {
        return mapper.selectScheduleDetail(doctorId, scheduleDate);
    }
    @Override
    public int insertOrUpdateSchedule(SysDoctorSchedule schedule) {
        SysDoctorSchedule exist = mapper.selectScheduleDetail(schedule.getDoctorId(), schedule.getScheduleDate());
        if (exist == null) {
            return mapper.insertSchedule(schedule);
        } else {
            return mapper.updateSchedule(schedule);
        }
    }
    @Override
    public int closeSchedule(Long doctorId, Date scheduleDate, String period) {
        return mapper.closeSchedule(doctorId, scheduleDate, period);
    }

    @Override
    public int insertSysDoctorSchedule(SysDoctorSchedule schedule) {
        return mapper.insertSysDoctorSchedule(schedule);
    }
}